package cn.itcast.web.exception;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义异常处理器
 *      实现HandlerExceptionResolver接口
 */
@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {


	/**
	 * resolveException ： 拦截所有的异常
	 *      * 一旦程序出现异常，自动的跳转到异常处理器的resolveException方法
	 *      * 参数 ： Exception（异常对象）
	 *      * 返回值 ： ModelAndView
	 *              * 通过返回值跳转公共的错误页面，携带错误信息
	 */
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

		/**
		 * 处理权限不足：UnauthorizedException
		 */
		if(ex instanceof UnauthorizedException){
			ModelAndView mv = new ModelAndView();
			mv.setViewName("redirect:/unauthorized.jsp");
			return mv;
		}else{
			ex.printStackTrace();
			ModelAndView mv = new ModelAndView();
			//1.设置需要跳转页面
			mv.setViewName("error");
			//2.配置错误信息
			mv.addObject("errorMsg","对不起，我错啦！");
			mv.addObject("ex",ex);
			return mv;
		}
	}
}
